<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>创建笔记 - SimpleNote</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- 引入wangEditor CSS（使用国内CDN） -->
    <link href="https://cdn.staticfile.org/wangEditor/10.0.13/wangEditor.min.css" rel="stylesheet">
    <!-- 引入wangEditor JS -->
    <script src="https://cdn.staticfile.org/wangEditor/10.0.13/wangEditor.min.js"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
            -webkit-font-smoothing: antialiased;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #ffffff;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            height: 100vh;
            width: 100vw;
            overflow: hidden;
            font-size: 16px;
        }
        
        /* 顶部导航栏 */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            background-color: #fff;
            border-bottom: 1px solid #eee;
            position: relative;
            z-index: 100;
        }
        
        .header .left a {
            color: #333;
            font-size: 16px;
            text-decoration: none;
        }
        
        .header .center {
            color: #888;
            font-size: 14px;
            text-align: center;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            white-space: nowrap;
        }
        
        .header .right button {
            color: #3478f6;
            background: none;
            border: none;
            font-size: 16px;
            padding: 0;
            outline: none;
        }
        
        /* 主编辑区域 */
        .editor-container {
            display: flex;
            flex-direction: column;
            height: calc(100vh - 45px);
            overflow: hidden;
            position: relative;
        }
        
        /* 自定义移动端工具栏 */
        .mobile-toolbar {
            display: flex;
            overflow-x: auto;
            background-color: #f9f9f9;
            border-bottom: 1px solid #eee;
            padding: 8px 6px;
            -webkit-overflow-scrolling: touch;
            position: sticky;
            top: 0;
            z-index: 99;
        }
        
        .mobile-toolbar::-webkit-scrollbar {
            display: none;
        }
        
        .mobile-toolbar button {
            min-width: 36px;
            height: 36px;
            border: none;
            background: transparent;
            color: #666;
            font-size: 18px;
            margin: 0 4px;
            padding: 0;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .mobile-toolbar button.with-text {
            min-width: 50px;
            font-size: 14px;
        }
        
        .mobile-toolbar button:active {
            background-color: rgba(0,0,0,0.05);
        }
        
        .mobile-toolbar .divider {
            width: 1px;
            height: 24px;
            background-color: #ddd;
            margin: 0 6px;
            flex-shrink: 0;
        }
        
        /* 编辑器区域 */
        .editor-wrapper {
            flex: 1;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        #editor {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;
            outline: none;
            -webkit-overflow-scrolling: touch;
        }
        
        /* 修改wangEditor的样式以适应移动端 */
        .w-e-toolbar {
            flex-wrap: wrap;
            border-bottom: 1px solid #eee !important;
            padding: 4px 0 !important;
        }
        
        .w-e-menu {
            padding: 8px 5px !important;
        }
        
        .w-e-text-container {
            height: auto !important;
            flex: 1 !important;
            min-height: calc(100vh - 135px) !important;
        }
        
        .w-e-text {
            padding: 10px 15px !important;
            min-height: calc(100vh - 135px) !important;
        }
        
        /* 自定义编辑器内容样式 */
        .w-e-text h1, .w-e-text h2, .w-e-text h3 {
            margin-top: 0.8em;
            margin-bottom: 0.5em;
        }
        
        .w-e-text p {
            margin-bottom: 0.8em;
        }
        
        .w-e-text ul, .w-e-text ol {
            padding-left: 2em;
            margin-bottom: 0.8em;
        }
        
        .w-e-text img {
            max-width: 100% !important;
            height: auto !important;
        }
        
        /* 字数统计 */
        .counter {
            position: fixed;
            bottom: 10px;
            right: 10px;
            padding: 4px 8px;
            color: #999;
            font-size: 12px;
            background-color: rgba(255,255,255,0.8);
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            z-index: 10;
        }
        
        /* 针对移动端的优化 */
        @media (max-width: 768px) {
            .header {
                padding: 8px 12px;
            }
            
            .mobile-toolbar button {
                min-width: 32px;
                height: 32px;
                font-size: 16px;
                margin: 0 3px;
            }
            
            .w-e-menu {
                padding: 6px 4px !important;
            }
            
            .counter {
                bottom: 8px;
                right: 8px;
                font-size: 11px;
                padding: 3px 6px;
            }
        }
        
        /* 标题输入区域样式 */
        .title-input-container {
            padding: 10px 16px;
            border-bottom: 1px solid #eee;
        }
        
        .title-input {
            width: 100%;
            font-size: 18px;
            font-weight: 600;
            padding: 8px 0;
            border: none;
            outline: none;
            background: transparent;
        }
        
        /* 标签输入区域样式 */
        .tags-input-container {
            padding: 8px 16px;
            border-bottom: 1px solid #eee;
            background-color: #f8f9fa;
        }
        
        .tags-wrapper {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 8px;
        }
        
        .tags-label {
            font-size: 14px;
            font-weight: 500;
            color: #666;
        }
        
        .tags-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .tag {
            display: inline-flex;
            align-items: center;
            background-color: #e6f2ff;
            color: #007bff;
            padding: 4px 8px;
            border-radius: 16px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .tag-remove {
            margin-left: 5px;
            cursor: pointer;
            font-weight: bold;
        }
        
        .tags-hint {
            font-size: 12px;
            color: #888;
            margin-top: 5px;
            text-align: right;
        }
        
        .tag-input {
            flex: 1;
            min-width: 100px;
            font-size: 14px;
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 16px;
            outline: none;
        }
        
        #add-tag-btn {
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 16px;
            padding: 6px 12px;
            font-size: 12px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        #add-tag-btn:hover {
            background-color: #0062cc;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="header">
        <div class="left">
            <a href="javascript:history.back()">取消</a>
        </div>
        <div class="center">
            草稿将自动保存
        </div>
        <div class="right">
            <button id="next-btn">保存</button>
        </div>
    </div>
    
    <!-- 编辑器容器 -->
    <div class="editor-container">
        <!-- 标题输入区域 -->
        <div class="title-input-container">
            <input type="text" id="note-title" placeholder="请输入标题..." class="title-input">
        </div>
        
        <!-- 标签输入区域 -->
        <div class="tags-input-container">
            <div class="tags-wrapper">
                <span class="tags-label">标签:</span>
                <div class="tags-list" id="tags-list"></div>
                <input type="text" id="tag-input" placeholder="添加标签...(最多3个)" class="tag-input">
                <button id="add-tag-btn">添加</button>
            </div>
            <div class="tags-hint">最多可添加3个标签</div>
        </div>
        
        <!-- 自定义移动端工具栏 -->
        <div class="mobile-toolbar">
            <button id="btn-h1" title="标题1"><i class="fas fa-heading"></i></button>
            <button id="btn-h2" title="标题2"><i class="fas fa-heading" style="font-size: 0.9em;"></i></button>
            <button id="btn-bold" title="粗体"><i class="fas fa-bold"></i></button>
            <button id="btn-italic" title="斜体"><i class="fas fa-italic"></i></button>
            <div class="divider"></div>
            <button id="btn-link" title="链接"><i class="fas fa-link"></i></button>
            <button id="btn-image" title="图片"><i class="fas fa-image"></i></button>
            <button id="btn-list-ul" title="无序列表"><i class="fas fa-list-ul"></i></button>
            <button id="btn-list-ol" title="有序列表"><i class="fas fa-list-ol"></i></button>
            <div class="divider"></div>
            <button id="btn-quote" title="引用"><i class="fas fa-quote-left"></i></button>
            <button id="btn-code" title="代码"><i class="fas fa-code"></i></button>
            <button id="btn-table" title="表格"><i class="fas fa-table"></i></button>
            <button id="btn-clear" title="清除格式" class="with-text">清除</button>
        </div>
        
        <!-- 编辑器包装器 -->
        <div class="editor-wrapper">
            <!-- 编辑区域 -->
            <div id="editor"></div>
        </div>
        
        <!-- 字数统计 -->
        <div class="counter">0 字</div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const counter = document.querySelector('.counter');
            const nextBtn = document.getElementById('next-btn');
            
            // 初始化编辑器
            const E = window.wangEditor;
            const editor = new E('#editor');
            
            // 自定义配置
            editor.customConfig.zIndex = 1;
            editor.customConfig.uploadImgShowBase64 = true;
            editor.customConfig.menus = []; // 清空默认菜单
            editor.customConfig.pasteFilterStyle = false; // 保留粘贴的样式
            editor.customConfig.pasteIgnoreImg = false; // 保留粘贴的图片
            editor.customConfig.showLinkImg = false; // 禁用网络图片
            
            // 设置编辑区域的placeholder
            editor.customConfig.placeholder = '输入内容...';
            
            // 监听内容变化
            editor.customConfig.onchange = function(html) {
                // 更新字数统计
                const textContent = editor.txt.text().length;
                counter.textContent = textContent + ' 字';
                
                // 自动保存
                autoSave(html);
            };
            
            // 创建编辑器
            editor.create();
            
            // 加载保存的内容
            const savedContent = localStorage.getItem('draft-content-html');
            if (savedContent) {
                editor.txt.html(savedContent);
            } else {
                // 设置默认欢迎内容
                editor.txt.html(getDefaultContent());
            }
            
            // 更新初始字数统计
            const initialTextLength = editor.txt.text().length;
            counter.textContent = initialTextLength + ' 字';
            
            // 自动保存功能
            let saveTimer = null;
            function autoSave(html) {
                if (saveTimer) {
                    clearTimeout(saveTimer);
                }
                
                saveTimer = setTimeout(() => {
                    const text = editor.txt.text();
                    
                    if (text.trim()) {
                        localStorage.setItem('draft-content-html', html);
                        localStorage.setItem('draft-content-text', text);
                        console.log('自动保存草稿:', new Date().toLocaleTimeString());
                    }
                }, 1000);
            }
            
            // 设置工具栏按钮事件
            setupToolbarEvents();
            
            // 设置自定义工具栏按钮事件
            function setupToolbarEvents() {
                // H1按钮
                document.getElementById('btn-h1').addEventListener('click', function() {
                    editor.cmd.do('formatBlock', '<h1>');
                    focusEditor();
                });
                
                // H2按钮
                document.getElementById('btn-h2').addEventListener('click', function() {
                    editor.cmd.do('formatBlock', '<h2>');
                    focusEditor();
                });
                
                // 粗体按钮
                document.getElementById('btn-bold').addEventListener('click', function() {
                    editor.cmd.do('bold');
                    focusEditor();
                });
                
                // 斜体按钮
                document.getElementById('btn-italic').addEventListener('click', function() {
                    editor.cmd.do('italic');
                    focusEditor();
                });
                
                // 链接按钮
                document.getElementById('btn-link').addEventListener('click', function() {
                    const url = prompt('请输入链接地址', 'https://');
                    if (url) {
                        editor.cmd.do('createLink', url);
                    }
                    focusEditor();
                });
                
                // 图片按钮
                document.getElementById('btn-image').addEventListener('click', function() {
                    const fileInput = document.createElement('input');
                    fileInput.type = 'file';
                    fileInput.accept = 'image/*';
                    fileInput.onchange = function() {
                        if (!this.files || !this.files[0]) return;
                        const file = this.files[0];
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            editor.cmd.do('insertHTML', `<img src="${e.target.result}" style="max-width:100%"/>`);
                            focusEditor();
                        };
                        reader.readAsDataURL(file);
                    };
                    fileInput.click();
                });
                
                // 无序列表按钮
                document.getElementById('btn-list-ul').addEventListener('click', function() {
                    editor.cmd.do('insertUnorderedList');
                    focusEditor();
                });
                
                // 有序列表按钮
                document.getElementById('btn-list-ol').addEventListener('click', function() {
                    editor.cmd.do('insertOrderedList');
                    focusEditor();
                });
                
                // 引用按钮
                document.getElementById('btn-quote').addEventListener('click', function() {
                    editor.cmd.do('formatBlock', '<blockquote>');
                    focusEditor();
                });
                
                // 代码按钮
                document.getElementById('btn-code').addEventListener('click', function() {
                    const selection = window.getSelection();
                    if (selection.toString().trim() !== '') {
                        editor.cmd.do('insertHTML', `<pre><code>${selection.toString()}</code></pre>`);
                    } else {
                        editor.cmd.do('insertHTML', '<pre><code>输入代码...</code></pre>');
                    }
                    focusEditor();
                });
                
                // 表格按钮
                document.getElementById('btn-table').addEventListener('click', function() {
                    editor.cmd.do('insertHTML', `
                    <table border="1" cellpadding="5" cellspacing="0" style="width:100%">
                        <tr><th>标题1</th><th>标题2</th></tr>
                        <tr><td>内容1</td><td>内容2</td></tr>
                        <tr><td>内容3</td><td>内容4</td></tr>
                    </table>
                    <p><br></p>`);
                    focusEditor();
                });
                
                // 清除格式按钮
                document.getElementById('btn-clear').addEventListener('click', function() {
                    editor.cmd.do('removeFormat');
                    focusEditor();
                });
            }
            
            // 聚焦编辑器
            function focusEditor() {
                setTimeout(() => {
                    editor.selection.restoreSelection();
                }, 10);
            }
            
            // 更新发布功能
            nextBtn.addEventListener('click', function() {
                const html = editor.txt.html();
                const text = editor.txt.text();
                const title = document.getElementById('note-title').value.trim();
                const tags = getTagsArray();
                
                if (!title) {
                    alert('请输入笔记标题');
                    return;
                }
                
                if (!text || text.trim() === '') {
                    alert('请输入笔记内容');
                    return;
                }
                
                // 创建笔记对象
                const note = {
                    id: Date.now().toString(),
                    title: title,
                    content: html,
                    text: text,
                    tags: tags,
                    author: '匿名用户',
                    publishedAt: new Date().toLocaleString(),
                    contentType: 'html'
                };
                
                // 模拟保存
                console.log('准备发布笔记:', note);
                alert('笔记发布成功！');
                
                // 清除草稿
                localStorage.removeItem('draft-content-html');
                localStorage.removeItem('draft-content-text');
                localStorage.removeItem('draft-title');
                localStorage.removeItem('draft-tags');
                
                // 跳转
                window.location.href = 'online-notes.html';
            });
            
            // 处理软键盘问题
            window.addEventListener('resize', function() {
                // 延迟执行，等待键盘完全显示
                setTimeout(() => {
                    const editorWrapper = document.querySelector('.editor-wrapper');
                    const toolbarHeight = document.querySelector('.mobile-toolbar').offsetHeight;
                    const headerHeight = document.querySelector('.header').offsetHeight;
                    const titleHeight = document.querySelector('.title-input-container').offsetHeight;
                    const tagsHeight = document.querySelector('.tags-input-container').offsetHeight;
                    const windowHeight = window.innerHeight;
                    
                    editorWrapper.style.height = `${windowHeight - toolbarHeight - headerHeight - titleHeight - tagsHeight}px`;
                    
                    // 将编辑区域滚动到可视区域
                    const selection = window.getSelection();
                    if (selection.rangeCount > 0) {
                        const range = selection.getRangeAt(0);
                        const rect = range.getBoundingClientRect();
                        if (rect.top > windowHeight || rect.bottom < 0) {
                            range.startContainer.parentElement.scrollIntoView({
                                behavior: 'smooth',
                                block: 'center'
                            });
                        }
                    }
                }, 300);
            });
            
            // 禁止双击缩放
            document.addEventListener('dblclick', function(e) {
                e.preventDefault();
            });
            
            // 初始化标签功能
            initTagsSystem();
        });
        
        // 获取所有标签为数组（全局函数）
        function getTagsArray() {
            const tagsList = document.getElementById('tags-list');
            return Array.from(tagsList.querySelectorAll('.tag')).map(tag => 
                tag.textContent.replace('×', '').trim()
            );
        }
        
        // 初始化标签系统
        function initTagsSystem() {
            const tagInput = document.getElementById('tag-input');
            const addTagBtn = document.getElementById('add-tag-btn');
            const tagsList = document.getElementById('tags-list');
            const titleInput = document.getElementById('note-title');
            
            // 更新标签输入框和按钮的可见性
            function updateTagInputVisibility() {
                const currentTags = getTagsArray();
                if (currentTags.length >= 3) {
                    tagInput.style.display = 'none';
                    addTagBtn.style.display = 'none';
                } else {
                    tagInput.style.display = '';
                    addTagBtn.style.display = '';
                }
            }
            
            // 创建标签元素
            function createTag(text) {
                // 检查标签是否已存在
                const existingTags = getTagsArray();
                
                if (existingTags.includes(text)) {
                    return; // 已存在相同标签，不再添加
                }
                
                const tag = document.createElement('div');
                tag.className = 'tag';
                tag.innerHTML = `${text} <span class="tag-remove">×</span>`;
                
                // 添加删除标签事件
                tag.querySelector('.tag-remove').addEventListener('click', function() {
                    tag.remove();
                    saveTags();
                    updateTagInputVisibility();
                });
                
                tagsList.appendChild(tag);
                
                // 更新标签输入框的可见性
                updateTagInputVisibility();
            }
            
            // 保存标签到localStorage
            function saveTags() {
                const tags = getTagsArray();
                localStorage.setItem('draft-tags', JSON.stringify(tags));
            }
            
            // 从localStorage加载标签
            function loadTags() {
                try {
                    const savedTags = localStorage.getItem('draft-tags');
                    if (savedTags) {
                        const tags = JSON.parse(savedTags);
                        // 只加载前三个标签
                        const tagsToLoad = tags.slice(0, 3);
                        tagsToLoad.forEach(tag => createTag(tag));
                    }
                    // 初始更新输入框可见性
                    updateTagInputVisibility();
                } catch (e) {
                    console.error('加载标签出错:', e);
                }
            }
            
            // 添加标签函数
            function addTag() {
                const tagText = tagInput.value.trim();
                if (tagText) {
                    // 检查标签数量是否已达到3个
                    const currentTags = getTagsArray();
                    if (currentTags.length >= 3) {
                        alert('最多只能添加3个标签');
                        return;
                    }
                    
                    createTag(tagText);
                    tagInput.value = '';
                    saveTags();
                }
            }
            
            // 加载保存的标题
            const savedTitle = localStorage.getItem('draft-title');
            if (savedTitle) {
                titleInput.value = savedTitle;
            }
            
            // 加载保存的标签
            loadTags();
            
            // 监听标题输入变化
            titleInput.addEventListener('input', function() {
                localStorage.setItem('draft-title', this.value);
            });
            
            // 添加标签按钮点击事件
            addTagBtn.addEventListener('click', function() {
                addTag();
            });
            
            // 按回车添加标签
            tagInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addTag();
                }
            });
        }
        
        // 默认欢迎内容
        function getDefaultContent() {
            return `<h1>欢迎使用简单编辑器</h1>
            <p>你好！这是你第一次使用 <strong>简单编辑器</strong> 所展示的欢迎页。如果你想使用编辑器，可以直接编辑这些文字。</p>
            <h3>功能特点</h3>
            <p>我们的编辑器包含如下几点功能，帮助你编写内容：</p>
            <ol>
                <li><strong>简洁的界面设计</strong>，带来轻松的写作体验；</li>
                <li><strong>丰富的格式支持</strong>，包括标题、粗体、斜体、列表、引用等；</li>
                <li>增加了 <strong>图片插入</strong> 功能，你可以插入本地图片；</li>
                <li>支持 <strong>移动端编辑</strong>，随时随地记录想法；</li>
                <li>内容自动保存，防止意外丢失。</li>
            </ol>`;
        }
    </script>
</body>
</html> 